#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件工具类
提供文件操作的通用功能
"""

import os
import shutil
from pathlib import Path
from typing import List, Optional
from core.utils_module.language_utils import collect_extensions, get_extension_group

def ensure_directory(directory_path: str) -> bool:
    """
    确保目录存在
    :param directory_path: 目录路径
    :return: 是否成功创建或已存在
    """
    try:
        os.makedirs(directory_path, exist_ok=True)
        return True
    except Exception as e:
        print(f"创建目录失败: {directory_path}, 错误: {e}")
        return False

def backup_file(source_path: str, backup_path: str) -> bool:
    """
    备份文件
    :param source_path: 源文件路径
    :param backup_path: 备份文件路径
    :return: 是否成功备份
    """
    try:
        ensure_directory(os.path.dirname(backup_path))
        shutil.copy2(source_path, backup_path)
        return True
    except Exception as e:
        print(f"备份文件失败: {source_path} -> {backup_path}, 错误: {e}")
        return False

def restore_file(backup_path: str, target_path: str) -> bool:
    """
    恢复文件
    :param backup_path: 备份文件路径
    :param target_path: 目标文件路径
    :return: 是否成功恢复
    """
    try:
        ensure_directory(os.path.dirname(target_path))
        shutil.copy2(backup_path, target_path)
        return True
    except Exception as e:
        print(f"恢复文件失败: {backup_path} -> {target_path}, 错误: {e}")
        return False

def get_file_size(file_path: str) -> int:
    """
    获取文件大小
    :param file_path: 文件路径
    :return: 文件大小（字节），失败返回0
    """
    try:
        return os.path.getsize(file_path)
    except:
        return 0

def get_file_extension(file_path: str) -> str:
    """
    获取文件扩展名
    :param file_path: 文件路径
    :return: 文件扩展名（小写）
    """
    return Path(file_path).suffix.lower()

def is_text_file(file_path: str) -> bool:
    """
    判断是否为文本文件
    :param file_path: 文件路径
    :return: 是否为文本文件
    """
    language_extensions = collect_extensions(['swift', 'objc', 'java', 'kotlin'])
    extra_extensions = {
        '.txt', '.py', '.cpp', '.c', '.hpp', '.json', '.plist'
    }
    xml_like = set(get_extension_group('xml_like'))
    text_extensions = language_extensions.union(extra_extensions).union(xml_like)
    return get_file_extension(file_path) in text_extensions

def read_file_safely(file_path: str, encoding: str = 'utf-8') -> Optional[str]:
    """
    安全读取文件
    :param file_path: 文件路径
    :param encoding: 文件编码
    :return: 文件内容，失败返回None
    """
    try:
        with open(file_path, 'r', encoding=encoding) as f:
            return f.read()
    except Exception as e:
        print(f"读取文件失败: {file_path}, 错误: {e}")
        return None

def write_file_safely(file_path: str, content: str, encoding: str = 'utf-8') -> bool:
    """
    安全写入文件
    :param file_path: 文件路径
    :param content: 文件内容
    :param encoding: 文件编码
    :return: 是否成功写入
    """
    try:
        ensure_directory(os.path.dirname(file_path))
        with open(file_path, 'w', encoding=encoding) as f:
            f.write(content)
        return True
    except Exception as e:
        print(f"写入文件失败: {file_path}, 错误: {e}")
        return False

def find_files_by_extension(directory: str, extensions: List[str]) -> List[str]:
    """
    根据扩展名查找文件
    :param directory: 目录路径
    :param extensions: 扩展名列表（小写）
    :return: 匹配的文件路径列表
    """
    files = []
    try:
        for root, dirs, filenames in os.walk(directory):
            for filename in filenames:
                if any(filename.lower().endswith(ext) for ext in extensions):
                    files.append(os.path.join(root, filename))
    except Exception as e:
        print(f"查找文件失败: {directory}, 错误: {e}")
    return files

def clean_directory(directory: str) -> bool:
    """清空目录"""
    try:
        if os.path.exists(directory):
            shutil.rmtree(directory)
        ensure_directory(directory)
        return True
    except Exception as e:
        print(f"清空目录失败: {directory}, 错误: {e}")
        return False

def copy_directory(source: str, destination: str) -> bool:
    """复制目录"""
    try:
        if os.path.exists(destination):
            shutil.rmtree(destination)
        shutil.copytree(source, destination)
        return True
    except Exception as e:
        print(f"复制目录失败: {source} -> {destination}, 错误: {e}")
        return False
